package org.hive.testserver.domain.model.schedule;

import org.hive.testserver.domain.model.Slave;
import org.hive.testserver.domain.model.Test;
import org.hive.testserver.domain.model.TestRun;
import org.hive.testserver.domain.model.WorkSheet;



public class ChainedAllocator implements TestPolicy {

	private AllocatorLink exemplar;

	public ChainedAllocator(AllocatorLink exemplar) {
		super();
		this.exemplar = exemplar;
	}
	
	public ScheduledTest nextTestOrNull(TestRun testRun, Slave slave, WorkSheet workSheet) {
		AllocatorLink head = prepareAllocator();
		for (Test test : testRun.getTests()) {
			if (! test.isFinished()) {
				head.accept(test, slave, workSheet);
			}
		}
		return head.scheduleNextTest(slave, workSheet);
	}

	private AllocatorLink prepareAllocator() {
		return exemplar.createWorkingCopy();
	}

	public void onRunStarted(TestRun testRun) {
		// do nothing
	}

	public void onTestStateUpdated(Test test) {
		if (prepareAllocator().shouldConsiderTestFinished(test)) {
			test.beFinished();
		}
	}
}
